package com.zzyl.nursing.service.impl;

import java.awt.*;
import java.util.List;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.common.utils.util.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import nonapi.io.github.classgraph.json.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 入住表Service业务层处理
 * 
 * @author 大黑牛
 * @date 2025-10-10
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住表
     * 
     * @param id 入住表主键
     * @return 入住表
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住表列表
     * 
     * @param checkIn 入住表
     * @return 入住表
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }

    /**
     * 修改入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住表
     * 
     * @param ids 需要删除的入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住表信息
     * 
     * @param id 入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //校验老人是否已入住  如果已入住直接抛异常BaseException
        //根据老人身份证号+状态状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）  从老人表中查询
        CheckInElderDto ElderDto = dto.getCheckInElderDto();
        CheckInContractDto ContractDto = dto.getCheckInContractDto();
        CheckInConfigDto ConfigDto = dto.getCheckInConfigDto();
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();

        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,ElderDto.getIdCardNo());
        wrapper.eq(Elder::getStatus,4);
        Elder elder = elderMapper.selectOne(wrapper);
        if (elder!=null){
            throw new BeanException("该老人已入住");
        }

        //更新床位的状态  update bed set bed_status = 1 where id=??
        //更新床位的状态
        Long bedId = ConfigDto.getBedId();
        Bed bed = bedMapper.selectBedById(bedId);
        if (bed==null){
            throw new BaseException("该床位为空的");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //新增或更新老人elder
        elder = saveOrupdateElder(ElderDto,bed);
        //新增合同信息  合同号要求： HT+18位数字，例：HT202501011012590001
        saveContract(ContractDto,elder,ConfigDto);
        //新增入住信息  老人家属信息存到remark字段中
        CheckIn checkIn = saveCheckIn(elder,elderFamilyDtoList,ConfigDto,bed);
        //新增入住配置
        saveCheckInConfig(ContractDto,elder,ConfigDto,checkIn);

    }

    private CheckIn saveCheckIn(Elder elder, List<ElderFamilyDto> elderFamilyDtoList,CheckInConfigDto ConfigDto,Bed bed) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(ConfigDto.getStartDate());
        checkIn.setEndDate(ConfigDto.getEndDate());
        checkIn.setNursingLevelName(ConfigDto.getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);

        String jsonStr = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(jsonStr);

        checkInMapper.insert(checkIn);

        return checkIn;


    }

    private void saveCheckInConfig(CheckInContractDto contractDto, Elder elder, CheckInConfigDto configDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelId(configDto.getNursingLevelId());
        checkInConfig.setNursingLevelName(configDto.getNursingLevelName());
        checkInConfig.setFeeStartDate(configDto.getFeeStartDate());
        checkInConfig.setFeeEndDate(configDto.getFeeEndDate());
        checkInConfig.setDeposit(configDto.getDeposit());
        checkInConfig.setNursingFee(configDto.getNursingFee());
        checkInConfig.setBedFee(configDto.getBedFee());
        checkInConfig.setInsurancePayment(configDto.getInsurancePayment());
        checkInConfig.setGovernmentSubsidy(configDto.getGovernmentSubsidy());
        checkInConfig.setOtherFees(configDto.getOtherFees());

        checkInConfigMapper.insert(checkInConfig);
    }

    private void saveContract(CheckInContractDto contractDto, Elder elder, CheckInConfigDto configDto) {
        Contract contract = new Contract();
        contract.setElderId(elder.getId());
        contract.setContractName(contractDto.getContractName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setAgreementPath(contractDto.getAgreementPath());
        contract.setThirdPartyPhone(contractDto.getThirdPartyPhone());
        contract.setThirdPartyName(contractDto.getThirdPartyName());
        contract.setElderName(elder.getName());
        contract.setStartDate(configDto.getStartDate());
        contract.setEndDate(configDto.getEndDate());
        contract.setStatus(1);
        contract.setSignDate(contractDto.getSignDate());
//        contract.setTerminationSubmitter();
//        contract.setTerminationDate();
//        contract.setTerminationAgreementPath();
//        contract.setSortOrder();
        contractMapper.insert(contract);

    }

    private Elder saveOrupdateElder(CheckInElderDto elderDto, Bed bed) {
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,elderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(wrapper);
        if (elder==null){
            elder = new Elder();
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());

            elderMapper.insert(elder);

        }else{
            elder.setName(elderDto.getName());
            elder.setImage(elderDto.getImage());
            elder.setIdCardNo(elderDto.getIdCardNo());
            elder.setSex(elderDto.getSex());
            elder.setStatus(4);
            elder.setPhone(elderDto.getPhone());
            elder.setBirthday(elderDto.getBirthday());
            elder.setAddress(elderDto.getAddress());
            elder.setIdCardNationalEmblemImg(elderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(elderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());

            elderMapper.updateById(elder);
        }
        return elder;
    }


//查询入住信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        CheckIn check = getById(id);
        Long elderId = check.getElderId();

        //查询老人信息
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo,check.getIdCardNo());
        Elder elder = elderMapper.selectOne(wrapper);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        int age = DateUtil.ageOfNow(elder.getBirthday());
        checkInElderVo.setAge(age);
        BeanUtils.copyProperties(elder,checkInElderVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //家属信息
        String remark = check.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        //合同
        LambdaQueryWrapper<Contract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
        contractLambdaQueryWrapper.eq(Contract::getElderId,elderId);
        Contract contract = contractMapper.selectOne(contractLambdaQueryWrapper);
        checkInDetailVo.setContract(contract);

        //入住配置
        LambdaQueryWrapper<CheckInConfig> checkInConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
        checkInConfigLambdaQueryWrapper.eq(CheckInConfig::getCheckInId,check.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigLambdaQueryWrapper);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(check.getStartDate());
        checkInConfigVo.setEndDate(check.getEndDate());
        checkInConfigVo.setBedNumber(check.getBedNumber());
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //返回checkInDetailVo，来查询
        return checkInDetailVo;
    }

//看看我
}
/*CheckIn checkIn = checkInMapper.selectById(id);
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getId, checkIn.getElderId());
        Elder elder = elderMapper.selectOne(wrapper);
       CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //家属成员
        String remark = checkIn.getRemark();
        List<Object> list = JSONUtil.toList(remark, ElderFamilyVo);
*/
